package cn.fzc.elasticsearch2x.service;

import cn.fzc.elasticsearch2x.dao.InvoiceMainRepository;
import cn.fzc.elasticsearch2x.entity.InvoiceDetail;
import cn.fzc.elasticsearch2x.entity.InvoiceMain;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

@Service
public class InvoiceMainService {

    @Autowired
    InvoiceMainRepository repository;
    @Autowired
    ElasticsearchTemplate template;


    Page<InvoiceMain> searchById(String id) {
        //创建builder
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //builder下有must、should以及mustNot 相当于sql中的and、or以及not
        //设置模糊搜索,真实姓名中包含金的用户
        builder.must(QueryBuilders.termQuery("_id", id));

        //排序
//        FieldSortBuilder sort = SortBuilders.fieldSort("update_time").order(SortOrder.DESC);

        //设置分页
        //====注意!es的分页和Hibernate一样api是从第0页开始的=========
        PageRequest page = new PageRequest(0, 2);

        //构建查询
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //将搜索条件设置到构建中
        nativeSearchQueryBuilder.withQuery(builder);
        //将分页设置到构建中
        nativeSearchQueryBuilder.withPageable(page);
        //将排序设置到构建中
//        nativeSearchQueryBuilder.withSort(sort);
        //生产NativeSearchQuery
        NativeSearchQuery query = nativeSearchQueryBuilder.build();

        //执行,返回包装结果的分页
        Page<InvoiceMain> resutlList = repository.search(query);
        return resutlList;
    }

    InvoiceMain findById(String id) {
        GetQuery query = new GetQuery();
        query.setId(id);// 索引的id
        return template.queryForObject(query, InvoiceMain.class);
    }
}
